package com.hitgo.soccer.handler;

import com.hitgo.soccer.config.TeamConfig;
import com.hitgo.soccer.core.Player;
import com.hitgo.soccer.core.Team;
import com.hitgo.soccer.database.PlayerDAO;
import com.hitgo.soccer.database.TeamDAO;

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TeamHandler extends BaseHandler
{
	private static BaseHandler instance = null;
	
	public static BaseHandler getInstance()
	{
		if(instance == null)
			instance = new TeamHandler();
		return instance;
	}

	@Override
	public void cmdHandler(int cmd, HttpServletRequest req,	HttpServletResponse res)
	{
		String strParams = req.getParameter("fbParams");
		switch(cmd)
		{
		case Commands.TEAM_INFO_GET:
			getTeam(res, strParams);	
			break;
		default:
			break;
		}
	}
	
	private void getTeam(HttpServletResponse res, String strParams)
	{
		strParams = strParams.trim();
		String[] params = strParams.split(Commands.PARAMS_SEPARATOR);
		Long lUserID = Long.parseLong(params[0]);

		byte[] data = getTeam(lUserID);
		res.setContentType("text/plain");
		try
		{
			ServletOutputStream out = res.getOutputStream();
			if(data == null)
				out.write(0);
			else
				out.write(data);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
	private byte[] getTeam(long lTeamID)
	{
		Team team = TeamDAO.getTeam(lTeamID);
		if(team == null)
		{
			team = newTeam(lTeamID);
			
		}
		
		return team.toByte();
	}
	
	private Team newTeam(long lTeamID)
	{
		Team team = new Team();
		
		team.setUserID(lTeamID);
		
		Player[] aP = new Player[TeamConfig.players.length];
		for(int nIndex =0; nIndex < TeamConfig.players.length; nIndex++)
		{
			Player p = TeamConfig.players[nIndex].clone();
			PlayerDAO.insertPlayer(p);
			aP[nIndex] = p;
		}
		team.setPlayers(aP);
		
		TeamDAO.insertTeam(team);
		return team;
	}
}